<?php
/**
 * Introduction: 系统设置逻辑
 * @author: 杨陈鹏
 * @email: yangchenpeng@cdlinglu.com
 */

namespace Common\Logic;

use Common\Model\SettingModel;

class SettingLogic
{

    static public $model;

    public function __construct()
    {

        self::$model = new SettingModel();

    }

    /**
     * Introduction: 设置
     * @author: 杨陈鹏
     * @email: yangchenpeng@cdlinglu.com
     * @param string $key
     * @param all $val ;
     * @param bool $is_create 是否需要创建
     */
    static public function set($key, $val, $description = '', $is_create = false)
    {

        if (!$key)
            return ['code' => 300, 'msg' => '缺少KEY'];

        if (!$val)
            return ['code' => 300, 'msg' => '缺少VALUE'];

        $val = serialize($val);

        if ($is_create && !self::$model->where(['key' => $key])->count()) {


            $data['key'] = $key;
            $data['value'] = $val;
            $data['description'] = $description;

            if (self::$model->add($data))
                return ['code' => 200, 'msg' => '设置成功!'];

        }

        $result = self::$model->where(['key' => $key])->setField(['value' => $val]);

        if($result === false)
            return ['code' => 300, 'msg' => '设置失败!'];

        if($result === 0)
            return ['code' => 300, 'msg' => '新的不能和旧的相同!'];


        if ($result)
            return ['code' => 200, 'msg' => '设置成功!'];

        return ['code' => 300, 'msg' => '设置失败!'];

    }

    /**
     * Introduction: 获取配置
     * @author: 杨陈鹏
     * @email: yangchenpeng@cdlinglu.com
     * @param string $key 多个使用逗号隔开
     */
    public function get($key)
    {

        if (!$key)
            return ['code' => 300, 'msg' => '缺少KEY'];

        if (!self::$model->where(['key' => $key])->count())
            return ['code' => 300, 'msg' => 'KEY不存在!'];

        $data = self::$model->where(['key' => $key])->getField('value');

        $data = unserialize($data);

        return ['code' => 200, 'data' => $data];


    }
}